package com.kebaijia.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author luoy
 * @date 2018/7/24 0024 上午 9:05
 * @Description: ${todo}
 */
public class AioServer {
    public static void main(String[] args) throws Exception {
        //获得Aio服务的对象
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();

        //绑定端口
        server.bind(new InetSocketAddress(9000));
        //第一张实现方法
        //Future<AsynchronousSocketChannel> future = server.accept();//等待客户端连接，不会阻塞
        //AsynchronousSocketChannel channel = future.get();

        /**
         *  第二种实现方法
         *
         *  参数1：附件，多线程交换数据用
         *  参数2：接口回调，操作完成时的处理器,一旦有客户端连接服务器，系统回调这个接口
         */

        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            //连接成功了要做什么
            @Override
            public void completed(AsynchronousSocketChannel channel, Object attachment) {
                try {
                    System.out.println("连接成功");

                    ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
                    //不能保证数据完全发送出去，因为是异步的
                    Future<Integer> future = channel.write(buffer);

                    future.get();
                    channel.close();
                    server.accept(null,this);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
            //连接失败了要做什么
            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });

        System.out.println("main go on");
        while (true){
            Thread.sleep(1000);
        }
    }
}
